package com.tengju.user.application.protocol;

import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.shared.ApplicationExceptionCode;
import com.tengju.user.domain.model.protocol.*;
import com.tengju.user.domain.shared.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class AppVersionService {

    @Value("${app.ios.version}")
    String iosVersion;

    @Value("${app.android.version}")
    String androidVersion;


    public AppVersionCheckResult checkVersion(ReqPlatform reqPlatform, String appVersion) {

        AppVersionInfo appVersionInfo;

        if (reqPlatform == ReqPlatform.IOS) {
            appVersionInfo = JsonUtil.toObject(iosVersion, AppVersionInfo.class);
        } else if (reqPlatform == ReqPlatform.ANDROID) {
            appVersionInfo = JsonUtil.toObject(androidVersion, AppVersionInfo.class);
        } else {
            throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"客户端平台错误");
        }

        if (appVersionInfo == null) {
            throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"客户端版本错误");
        }

        boolean isNew = true;
        if (appVersionInfo.compareVersion(appVersion) > 0) {
            isNew = false;
        }

        return new AppVersionCheckResult(isNew,appVersionInfo);



    }


}
